package com.accp.restaurant.Realm;

import com.accp.restaurant.dao.PermissionDao;
import com.accp.restaurant.dao.StaffDao;
import com.accp.restaurant.entity.Permission;
import com.accp.restaurant.entity.Staff;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 身份验证
 */
public class MyRealm extends AuthorizingRealm {


    @Autowired
    private StaffDao staffDao;
    @Autowired
    private PermissionDao permissionDao;


    /**
     * 认证用户信息
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String name = (String) authenticationToken.getPrincipal();
        Staff staff = staffDao.Login(name);
        if(staff!=null){
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(staff,staff.getStaffpwd(),"xx");
            return authenticationInfo;
        }else{
            return  null;
        }
    }
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        Staff staff = (Staff) subject.getPrincipal();
        List<Permission> list = permissionDao.getAll(staff.getRole().getRoleid());
        authorizationInfo.addRole(staff.getRole().getRolename());
            for(Permission p:list){
                authorizationInfo.addStringPermission(p.getPername());
            }
        return authorizationInfo;
    }


}
